package com.keyancompany.zhongbaopingtai.weight;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.ZBApplication;
import com.keyancompany.zhongbaopingtai.model.Update;
import com.keyancompany.zhongbaopingtai.ui.BaseDialog;
import com.keyancompany.zhongbaopingtai.utils.ScreenUtils;

public class UpdateDialog extends BaseDialog {

    private String saveFileName;

    private LinearLayout updateParent;
    private TextView udpateTitle;
    private TextView updateContent;
    private TextView cancel;
    private TextView sure;

    private RelativeLayout progressParent;
    private ProgressBar progressBar;
    private TextView size;
    private TextView currentProgress;

    private Update update;

    public UpdateDialog(Context context) {
        super(context, R.style.wihte_DialogStyle);

    }

    public void setUpViews() {
        // TODO Auto-generated method stub
        updateParent = (LinearLayout) findViewById(R.id.warning_parent);
        udpateTitle = (TextView) findViewById(R.id.update_title_hint);
        updateContent = (TextView) findViewById(R.id.update_conetnt);
        cancel = (TextView) findViewById(R.id.update_cancel);
        sure = (TextView) findViewById(R.id.update_sure);

        progressParent = (RelativeLayout) findViewById(R.id.progress_parent);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        size = (TextView) findViewById(R.id.app_total_size);
        currentProgress = (TextView) findViewById(R.id.app_update_progress);

        saveFileName = context.getResources().getString(R.string.app_name);
        setCanceledOnTouchOutside(false);
    }

    public void updateView(final Update update) {
        this.update = update;
        if (TextUtils.isEmpty(update.updateContent)) {
            updateContent.setVisibility(View.GONE);
            udpateTitle.setVisibility(View.GONE);
        } else {
            updateContent.setVisibility(View.VISIBLE);
            udpateTitle.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(update.appSize)) {
            size.setText("0");
        } else {
            size.setText(update.appSize);
        }

        setOnKeyListener(keylistener);
        saveFileName = saveFileName.concat(update.version);

        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (cancleListener != null) {
                    cancleListener.OnClickCancleBtn();
                }
                dismiss();
            }
        });

        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (okListener != null) {
                    okListener.OnClickSuccessBtn(null);
                }
                updateParent.setVisibility(View.GONE);
                progressParent.setVisibility(View.VISIBLE);
                downloadApk();

            }
        });

        if (update.updateType != 1) {
            cancel.setOnClickListener(null);
        }
    }

    public int getFlag() {
        return update.updateType;
    }

    OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0
                    && update.updateType == 1) {
                return true;
            } else {
                return false;
            }
        }
    };

    public int getContentView() {
        return R.layout.dialog_update;
    }

    protected int getDialogWidth() {
        return ScreenUtils.getScreenWidth(context) * 2 / 3;
    }

    public int getDialogHeight() {
        return 0;
    }

    public int getContentGravity() {
        return 0;
    }

    /**
     * 下载apk
     *
     * @param url
     */
    private Thread downLoadThread;

    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     */
    private void installApk() {
        dismiss();

        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        context.startActivity(i);

    }

    boolean canceled = false;
    int progress = 0;
    public int lastRate = 0;
    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(update.appUrl);
                // L.i("info", "====" + Constants.UPDATA_URL);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                int length = conn.getContentLength();
                // // 更新进度
                Message msg1 = mHandler.obtainMessage();
                msg1.what = 2;
                msg1.arg1 = length;
                mHandler.sendMessage(msg1);
                // // progressBar.setMax(msg.arg2);
                InputStream is = conn.getInputStream();

                File file = new File(Constants.FILE_PATH);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File ApkFile = new File(Constants.FILE_PATH + saveFileName);
                FileOutputStream fos = new FileOutputStream(ApkFile);
                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = progress;
                    msg.arg2 = length;
                    if (progress >= lastRate + 1) {
                        mHandler.sendMessage(msg);
                        lastRate = progress;
                        Log.i("info", lastRate + "=======" + "内部的数据======"
                                + progress + "");
                    }
                    if (numread <= 0) {
                        lastRate = 0;
                        // 下载完成通知安装
                        mHandler.sendEmptyMessage(0);
                        // 下载完了，cancelled也要设置
                        canceled = true;
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!canceled);// 点击取消就停止下载.

                fos.close();
                is.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    // 下载完毕
                    // 取消通知
                    dismiss();
                    installApk();
                    break;
                case 1:
                    // int rate = msg.arg1;
                    if (progressBar != null) {
                        currentProgress.setText(msg.arg1 + "%");
                        progressBar.setProgress(msg.arg1);
                    }
                    break;
                case 2:
                    // // 下载完毕
                    // // 取消通知
                    // dismiss();
                    // installApk();
                    size.setText(bytes2kb(msg.arg1));
                    break;
            }
        }
    };

    /**
     * @param bytes
     * @return
     * @Description long转文件大小M单位方法
     * @author temdy
     */
    public String bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        return returnValue + "MB";
    }
}
